<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use app\common\facade\Request;
use think\Db;

final class QRcodeLogin{

	/**
	 * 检查二维码是否有效
	 *
	 * @param string $token
	 * @param mixed  $uid
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function check($token, &$uid){
		$info = Db::name('qrcode_login')->where('token', $token)->find();
		if(empty($info)){
			return false;
		}

		if($info['expire_time'] < Request::time()){
			return false;
		}

		$uid = $info['uid'];
		return true;
	}

	/**
	 * 添加一个二维码待登录记录
	 *
	 * @param string $token 32 chars
	 * @param int    $from 0 and 1
	 * @param int    $expire
	 * @return bool
	 */
	public static function make($token, $from = 0, $expire = 300){
		$rows = Db::name('qrcode_login')->insert([
			'token'       => $token,
			'uid'         => 0,
			'from'        => $from,
			'ip'          => Request::ip(),
			'expire_time' => Request::time() + $expire,
		]);
		return $rows != 0;
	}

	/**
	 * 绑定UID到登录二维码
	 *
	 * @param string $token
	 * @param int    $uid
	 * @param mixed  $info
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public static function bindUid($token, $uid, &$info = null){
		$info = Db::name('qrcode_login')->where('token', $token)->find();
		if(empty($info)){
			return false;
		}

		$expireTime = $info['expire_time'];
		if($expireTime < Request::time()){
			return false;
		}

		Db::name('qrcode_login')->where('token', $token)->update([
			'uid' => $uid,
		]);

		return true;
	}
}
